package com.yingdong.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBManager {
	static Log logger = LogFactory.getLog(DBManager.class);
	private static ComboPooledDataSource ds;
	private static ReentrantLock lock = new ReentrantLock();

	public static void init() throws Exception {
		Properties prop = new Properties();
		File f = new File("conf/mybatis.properties");
		InputStream in = new FileInputStream(f);
		prop.load(in);
		ds = new ComboPooledDataSource("dataSource");
		ds.setDriverClass(prop.getProperty("db.driver"));
		ds.setJdbcUrl(prop.getProperty("db.url"));
		ds.setUser(prop.getProperty("db.username"));
		ds.setPassword(prop.getProperty("db.password"));
		ds.setPreferredTestQuery(prop.getProperty("db.preferredTestQuery"));
		ds.setMaxPoolSize(50);
		ds.setMaxIdleTime(300);
	}

	public static Connection getConnection() throws Exception {
		if (ds == null) {
			init();
		}
		try {
			lock.lock();
			Connection conn = ds.getConnection();
			return conn;
		} finally {

			lock.unlock();
		}
	}

	public static void closeConnection(Connection conn) {

		if (conn != null) {
			try {
				lock.lock();
				conn.close();
			} catch (SQLException e) {

				logger.error("", e);
			} finally {
				lock.unlock();
			}

		}
	}

}
